/*
 * Copyright 2009 Yannick Stucki (yannickstucki.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.yannickstucki.android.musicqueue;

import java.util.ArrayList;
import java.util.Collections;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.MediaStore;

/**
 * Fetches the songs from the MediaStore so they can be updated. This might take
 * a few seconds and runs therefore in its own thread.
 * 
 * @author Yannick Stucki (yannickstucki@gmail.com)
 * 
 */
public class SongUpdater implements Runnable {

  /**
   * A reference to the context to obtain the MediaStore.
   */
  private Context context;
  
  /**
   * A handler to notifiy when the update is done.
   */
  private SongUpdatedHandler handler;

  /**
   * The constructor needs to set those two important references.
   */
  public SongUpdater(Context context, SongUpdatedHandler handler) {
    this.context = context;
    this.handler = handler;
  }

  /**
   * A list of all songs.
   */
  private ArrayList<Song> allSongs = new ArrayList<Song>();

  @Override
  public void run() {
    allSongs.clear();
    ContentResolver resolver = context.getContentResolver();

    Cursor cursor = resolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
        new String[] { MediaStore.Audio.Media.TITLE,
            MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.ARTIST,
            MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.DURATION,
            MediaStore.Audio.Media.IS_MUSIC }, null, null, null);

    // No Songs found. Music player not functional. A message will be displayed.
    if (cursor == null) {
      Logger.out("No Songs Found");
      return;
    }

    cursor.moveToFirst();

    while (cursor.moveToNext()) {
      // Logger.debug(cursor.getString(3));
      allSongs.add(new Song(cursor));
    }
    Collections.sort(allSongs);
    int numberOfSongs = allSongs.size();
    for (int i = 0; i < numberOfSongs; i++) {
      allSongs.get(i).index = i;
    }
    if (handler != null) {
      handler.onSongsUpdated();
    }
  }

  /**
   * Returns all the songs found.
   */
  public ArrayList<Song> getSongs() {
    return allSongs;
  }
}
